package com.hyk.commonLib.common.utils.dataCache;

import com.hyk.commonLib.common.utils.AppUtils;
import com.hyk.commonLib.common.utils.GsonUtils;
import com.hyk.commonLib.common.utils.SoftHashMap;
import com.orhanobut.hawk.GsonParser;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.hawk.NoEncryption;


/**
 * Created by 贺玉琨 on 2019/3/6 0006.
 */
public class BaseDataCacheUtils {
    protected static final SoftHashMap<String, Object> MEM_CACHE_MAP = new SoftHashMap<>();

    public static void init() {
        Hawk.init(AppUtils.getAppContext())
                .setStorage(new MmkvStorage(AppUtils.getAppContext()))
                .setParser(new GsonParser(GsonUtils.getInstance()))
                .setEncryption(new NoEncryption())
                .build();
    }

    public synchronized static <T> void put(String key, T value) {
        Hawk.put(key, value);
        MEM_CACHE_MAP.put(key, value);
    }

    public synchronized static <T> T get(String key) {
        return Hawk.get(key);
    }

    public synchronized static <T> T get(String key, T defaultVal) {
        T value = (T) MEM_CACHE_MAP.get(key);
        if (value != null) return value;
        value = Hawk.get(key, defaultVal);
        if (value != defaultVal) {
            MEM_CACHE_MAP.put(key, value);
        }
        return value;
    }

    public static void delete(String key) {
        Hawk.delete(key);
        MEM_CACHE_MAP.remove(key);
    }

    public static void deleteAll() {
        Hawk.deleteAll();
        MEM_CACHE_MAP.clear();
    }

    public static boolean contains(String key) {
        return MEM_CACHE_MAP.containsKey(key) || Hawk.contains(key);
    }

    public static class CacheItem<T> {
        protected final String cacheKey;
        protected final T defaultValue;

        public CacheItem(String cacheKey) {
            this(cacheKey, null);
        }

        public CacheItem(String cacheKey, T defaultValue) {
            this.cacheKey = cacheKey;
            this.defaultValue = defaultValue;
        }

        public synchronized void put(T value) {
            BaseDataCacheUtils.put(cacheKey, value);
        }

        public synchronized T get() {
            return BaseDataCacheUtils.get(cacheKey, defaultValue);
        }

        public synchronized void delete() {
            BaseDataCacheUtils.delete(cacheKey);
        }
    }
}
